//
//  JOString.cpp
//  JOlib
//
//  Created by Pang Jun on 12/8/12.
//  Copyright (c) 2012 Pang Jun. All rights reserved.
//

#include "jo_string.h"

JOString::JOString()
:value('\0'),
lenth(0)
{
}

JOString::JOString (const char* val)
{
    long long srcLen = 0;
    const char * srcTmpPt;
    srcTmpPt = val;
    while (*srcTmpPt != '\0')
    {
        srcLen ++;
        srcTmpPt++;
    }
    if (srcLen > 0)
    {
        value = new char [srcLen + 1];
        value[srcLen] = '\0';
        srcTmpPt = val;
        char * decTmpPt = value;
        while (*srcTmpPt != '\0')
        {
            *decTmpPt++ = *srcTmpPt++;
        }
        lenth = srcLen;
    }
    else
    {
        value = '\0';
        lenth = 0;
    }
}

JOString::JOString(const JOString &ins)
{
    lenth = ins.lenth;
    value = new char [lenth + 1];
    value[lenth] = '\0';
    char * srcTmpPt = ins.value;
    char * decTmpPt = value;
    while (*srcTmpPt != '\0')
    {
        *decTmpPt++ = *srcTmpPt++;
    }
}

JOString::~JOString()
{
    delete value;
}

const JOString JOString::operator + (const JOString & joString)
{
    long long newLenth = lenth + joString.lenth;
    char * newJOString = new char[newLenth + 1];
    newJOString[newLenth] = '\0';
    char * srcTmpPt1 = value;
    char * srcTmpPt2 = joString.value;
    char * decTmpPt = newJOString;
    while (*srcTmpPt1 != '\0')
    {
        *decTmpPt++ = *srcTmpPt1++;
    }
    while (*srcTmpPt2 != '\0')
    {
        *decTmpPt++ = *srcTmpPt2++;
    }
    return JOString(newJOString);
}

char * JOString::String() const
{
    return value;
}

long long JOString::GetLenth() const
{
    return lenth;
}

char JOString::GetCharByIndex(const long long index) const
{
    if (index > 0 && index <= lenth)
    {
        return value[index - 1];
    }
    return '\0';
}

JOString JOString::GetSubStringByRange(const long long firstIndex, const long long secondIndex) const
{
    if (firstIndex < secondIndex)
    {
        char * subString = new char [secondIndex - firstIndex + 2];
        subString[secondIndex - firstIndex + 1] = '\0';
        char * subPt = subString;
        char * srcPt = value;
        for (long long i = 0; i < firstIndex - 1; i++)
        {
            srcPt++;
        }
        for (long long i = 0; i < (secondIndex - firstIndex +1); i++)
        {
            *subPt++ = *srcPt++;
        }
        return JOString(subString);
    }
    return nullptr;
}

long long JOString::FindChar(char targetChar, long long times)
{
    if (times < 0)
    {
        return -1;
    }
    long long tmpTimes = 0;
    for (long long i = 0; i < lenth; i ++)
    {
        if (GetCharByIndex(i + 1) == targetChar)
        {
            tmpTimes ++;
            if (times == tmpTimes)
            {
                return i + 1;
            }
        }
    }
    return 0;
}